package org.xx.armory.config;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

import java.util.Base64;

/**
 * 用于将Base64格式的字符串转化为字节数组的转化器。
 * <p>此类型用于{@link org.apache.commons.beanutils.BeanUtils}创建Bean。</p>
 */
public final class Base64Converter
        implements Converter {

    /**
     * {@inheritDoc}
     */
    @Override
    public <T> T convert(
            Class<T> clazz,
            Object o
    )
            throws ConversionException {
        if (o == null) {
            return null;
        }
        if (clazz != byte[].class) {
            throw new ConversionException("cannot convert " + o + " to " + clazz);
        }
        if (!(o instanceof CharSequence)) {
            throw new ConversionException("cannot convert " + o + " to " + clazz);
        }

        try {
            return clazz.cast(Base64.getDecoder().decode(o.toString().trim()));
        } catch (IllegalArgumentException | ClassCastException ex) {
            throw new ConversionException("cannot decode base64 string", ex);
        }
    }
}
